<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\admin\model;

use think\facade\Cache;

/**
 * 菜单模型
 * Class Menu
 * @package app\admin\model
 */
class Menu extends ManageBase
{

    /**
     * @package 查询结果
     * @param $order
     * @param $map
     * @param $page_config
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getDataList($page_config, $map, $order)
    {
        $data = $this
            ->where($map)
            ->order($order)
            ->paginate($page_config);
        return $data;
    }
    /**
     *  搜索
     * @param array $map
     * @param array $map2
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getAll($map=array(), $map2=array())
    {

        if (!empty(input('get.key'))  &&!empty(input('get.key_val'))) {
            $map[input('get.key')] = array('like', '%'.input('get.key_val').'%');
        }
        if (!empty(input('get.cat_id')) && is_numeric(input('get.cat_id')) && input('get.cat_id') > 0) {
            $map['contract'] = input('get.cat_id');
        }
        if (!empty(input('get.deal_type')) && is_numeric(input('get.deal_type')) && input('get.deal_type') > 0) {
            $map['deal_type'] = input('get.deal_type');
        }

        if (is_numeric(input('get.status'))) {
            $map['status'] = input('get.status');
        }

        $s1 = strtotime(input('get.posttime1'));
        $s2 = strtotime(input('get.posttime2'));

        if ($s1 && $s2 && $s1 < $s2) {
            $map['add_time'] =  array(['>=',$s1],['<=',$s2],'and');
        }
        if ($s1 && !$s2) {
            $map['add_time'] = array('egt', $s1);
        }
        if (!$s1 && $s2) {
            $map['add_time'] = array('elt', $s2);
        }

        $list = $this
            ->order('id desc')
            ->where($map)
            ->where($map2)
            ->paginate(10,false,['query' => request()->param()]);
        return $list;
    }

    /**
     * 按父ID查找菜单子项
     * @param $parentId
     * @param bool $withSelf
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminMenu($parentId, $withSelf = false)
    {
        $authModel = new AuthAccess();
        //父节点ID
        $parentId = (int)$parentId;
        $result   = $this
            ->where(['parent_id' => $parentId, 'status' => 1])
            ->order("list_order", "ASC")
            ->select();

        if ($withSelf) {
            $result2[] = $this->where(['id' => $parentId])->find();
            $result    = array_merge($result2, $result);
        }

        //权限检查
        if (session('admin_id') == 1) {
            //如果是超级管理员 直接通过
            return $result;
        }

        $array = [];

        foreach ($result as $v) {

            //方法
            $action = $v['action'];
            if (preg_match('/^ajax_([a-z]+)_/', $action, $_match)) {

                $action = $_match[1];
            }
            $rule_name = strtolower($v['app'] . "/" . $v['controller'] . "/" . $action);

            if ($v['param']) {
                $rule_name = strtolower($v['app'] . "/" . $v['controller'] . "/" . $action . '?' . $v['param']);
            }
            if ($authModel->checkRule(session('admin_id'), $rule_name)) {
                $array[] = $v;
            }

        }
        return $array;
    }

    /**
     * 取得树形结构的菜单
     * @param $myId
     * @param string $parent
     * @param int $Level
     * @return bool|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTree($myId, $parent = "", $Level = 1)
    {
        $data = $this->adminMenu($myId);

        $Level++;
        if (count($data) > 0) {
            $ret = NULL;
            foreach ($data as $a) {
                $id         = $a['id'];
                $name       = $a['app'];
                $controller = ucwords($a['controller']);
                $action     = $a['action'];
                //附带参数
                $params = "";
                if ($a['param']) {
                    $params = "?" . htmlspecialchars_decode($a['param']);
                }
                $array = [
                    "id"     => $id . $name,
                    "name"   => $a['name'],
                    "parent" => $parent,
                    "url"    => url("{$name}/{$controller}/{$action}{$params}"),
                    "route"    => $a['route']
                ];


                $ret[$id . $name] = $array;
                $child            = $this->getTree($a['id'], $id, $Level);
                //由于后台管理界面只支持三层，超出的不层级的不显示
                if ($child && $Level <= 3) {
                    $ret[$id . $name]['items'] = $child;
                }

            }
            return $ret;
        }

        return false;
    }

    /**
     * 更新缓存
     * @param  $data
     * @return array
     */
    public function menuCache($data = null)
    {

        if (empty($data)) {
            $data = $this->order("list_order", "ASC")->column('*');
            Cache::set('Menu', $data, 0);
        } else {
            Cache::set('Menu', $data, 0);
        }
        return $data;
    }

    /**
     * @param $parentId
     * @param bool $with_self
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function menu($parentId, $with_self = false)
    {
        //父节点ID
        $parentId = (int)$parentId;
        $result   = $this->where(['parent_id' => $parentId])->select();
        if ($with_self) {
            $result2[] = $this->where(['id' => $parentId])->find();
            $result    = array_merge($result2, $result);
        }
        return $result;
    }
}
